package com.baichen.spring.web;

import com.baichen.spring.Autowired;
import com.baichen.spring.Component;
import com.baichen.spring.PostConstruct;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.slf4j.bridge.SLF4JBridgeHandler;

import java.io.File;
import java.util.logging.LogManager;

@Component
public class TomcatServer {

    @Autowired
    private DispatcherServlet dispatcherServlet;

    @PostConstruct
    public void start() {
        loggerInstall();

        int port = 8081;
        Tomcat tomcat = new Tomcat();
        tomcat.setPort(port);
        tomcat.getConnector();

        String contextPath = "";
        String docBase = new File(".").getAbsolutePath();
        Context ctx = tomcat.addContext(contextPath, docBase);

        tomcat.addServlet(ctx, "dispatcherServlet", dispatcherServlet);
        ctx.addServletMappingDecoded("/*", "dispatcherServlet");
        try {
            tomcat.start();
        } catch (LifecycleException e) {
            throw new RuntimeException("Failed to start Tomcat server", e);
        }

        System.out.println("Tomcat server started: http://localhost:" + port + contextPath);
    }

    private static void loggerInstall() {
        LogManager.getLogManager().reset();
        SLF4JBridgeHandler.removeHandlersForRootLogger();
        SLF4JBridgeHandler.install();
    }
}
